package com.suning.park.web.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;

/**
 * BigDecimal工具类,默认保留两位小数
 *
 * @author niecheng
 */
public class BigDecimalUtil {

    private static final Logger logger = LoggerFactory.getLogger(BigDecimalUtil.class);

    private BigDecimalUtil() {

    }

    /**
     * 字符串转换为BigDecimal,保留两位小数，如果不符合BigDecimal格式，返回null
     *
     * @param str
     * @return
     */
    @SuppressWarnings("finally")
    public static BigDecimal strToBigDecimal(String str) {
        if (CheckValue.isEmpty(str)) {
            return null;
        }
        BigDecimal result = null;
        try {
            result = new BigDecimal(str).setScale(2, BigDecimal.ROUND_HALF_UP);
        } catch (NumberFormatException e) {
            logger.error("字符串转换BigDecimal出错，字符串：{}；错误信息：{}", str, e);
        } catch (Exception e) {
            logger.error("字符串转换BigDecimal出错，字符串：{}；错误信息：{}", str, e);
        } finally {
            return result;
        }
    }

    /**
     * 转换为字符串，保留两位小数
     *
     * @param amount
     * @return
     */
    public static String toString(BigDecimal amount) {
        if (null == amount) {
            return "0.00";
        }
        return String.valueOf(amount.setScale(2, BigDecimal.ROUND_HALF_UP));
    }

}
